//
//  WeiboLoginViewController.m
//  notebook
//
//  Created by 诗彬 刘 on 12-5-14.
//  Copyright (c) 2012年 ifuninfo. All rights reserved.
//

#import "WeiboLoginViewController.h"
#import "RIButtonItem.h"
#import "UIAlertView+Blocks.h"
#import "EasyBuy.h"

@interface WeiboLoginViewController()<UIWebViewDelegate, GHWeiboRequestDelegate>{
    UIActivityIndicatorView *indicatorView;
    UIWebView *webView;
}
@property(nonatomic,retain)GHWeiboEngine *weiboEngine;
@end

@implementation WeiboLoginViewController
@synthesize weiboEngine;

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kGHWeiboEngineLoginedNotification
                                                  object:nil];
    [indicatorView release];
    webView.delegate = nil;
    [webView release];
    [weiboEngine release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
     
    }
    return self;
}

- (id)initWithWeiboEngine:(GHWeiboEngine *)engine{
    self = [self init];
    if (self) {
        self.weiboEngine = engine;
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor colorWithRed:229.0f/255.0f green:231.0/255.0f blue:233.0f/255.0f alpha:1]];
    
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];//CGRectMake(200, 0, 400, 495)
    if ([webView respondsToSelector:@selector(scrollView)]) {
         webView.scrollView.scrollEnabled = NO;
    }
    webView.backgroundColor = self.view.backgroundColor;
    [webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    [webView setDelegate:self];
    webView.scalesPageToFit = YES;
    [self.view addSubview:webView];
    webView.hidden = YES;
    
    indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicatorView.center = self.view.center;
    [indicatorView setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin];
    [self.view addSubview:indicatorView];
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            weiboEngine.appKey,@"client_id",
                            @"code", @"response_type",
                            @"http://",@"redirect_uri",
                            @"mobile",@"display",nil];
    NSString *urlString = [NSString WBRequestURLWithBaseURL:SinaWeiboAuthorizeURL
                                                     params:params
                                                 httpMethod:@"GET"];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                          cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                      timeoutInterval:60.0]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(weiboDidLogin:)
                                                 name:kGHWeiboEngineLoginedNotification
                                               object:nil];
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [webView release];
    webView = nil;
    [indicatorView release];
    indicatorView = nil;
    // Release any retained subviews of the main view.
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (weiboEngine.isLogined) {
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

- (void)weiboDidLogin:(NSNotification *)notification{
    if (notification.object == weiboEngine) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)webViewDidStartLoad:(UIWebView *)aWebView{
	[indicatorView startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)aWebView{
    webView.hidden = NO;
	[indicatorView stopAnimating];
}

- (void)webView:(UIWebView *)aWebView didFailLoadWithError:(NSError *)error{
    [indicatorView stopAnimating];
    if (error.code == -1009) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"网络连接错误，请检查网络后重试" 
                                               cancelButtonItem:[RIButtonItem itemWithLabel:@"好"
                                                                                     action:^{
                                                                                         [self.navigationController popViewControllerAnimated:YES];
                                                                                     }]
                                               otherButtonItems:nil];
        [alert show];
        [alert release];   
    }
}

- (BOOL)webView:(UIWebView *)aWebView 
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType{
    NSRange range = [request.URL.absoluteString rangeOfString:@"code="];
    
    if (range.location != NSNotFound){
        NSString *code = [request.URL.absoluteString substringFromIndex:range.location + range.length];
        if ([code isEqualToString:@"21330"]) {
            return NO;
        }
        [weiboEngine performSelector:@selector(requestAccessTokenWithAuthorizeCode:) withObject:code];
    }
    return YES;
}
@end
